import 'package:flutter/services.dart';

class PriceRangeTextInputFormatter extends TextInputFormatter {
  double minValue;
  double maxValue;

  PriceRangeTextInputFormatter({this.minValue = 0.0, this.maxValue = 0.0});

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    if (minValue < 0) {
      if (containsTwoOrMoreOccurrencesOfDash(newValue.text)) {
        // - 数量大于2
        return oldValue;
      }

      double? newNum = double.tryParse(newValue.text);
      if (newNum != null && newNum < minValue) {
        return TextEditingValue(
            text: '$minValue',
            selection: TextSelection.collapsed(offset: '$minValue'.length));
      }
      return newValue;
    }
    double? newNum = double.tryParse(newValue.text);
    if (newNum == null && minValue == 0) {
      return const TextEditingValue(
          text: '', selection: TextSelection.collapsed(offset: 0));
    } else if (newNum != null && minValue <= newNum && newNum <= maxValue) {
      return newValue;
    } else if (newNum != null && newNum < minValue) {
      return TextEditingValue(
          text: '$minValue',
          selection: TextSelection.collapsed(offset: '$minValue'.length));
    } else {
      return oldValue;
    }
  }

  bool containsTwoOrMoreOccurrencesOfDash(String input) {
    // 使用正则表达式查找两个或更多的连字符
    RegExp regex = RegExp(r'-');
    // findAll 方法返回所有匹配的迭代器
    Iterable<Match> matches = regex.allMatches(input);

    // 返回匹配的数量是否大于或等于2
    return matches.length >= 2;
  }
}
